<template>
  <div>
    <el-drawer :visible="drawerEditBoolen"
               :before-close="handleClose"
               title="新增/编辑站点"
               ref="drawer"
               size="700px">
      <!-- 主体信息 -->
      <div class="ele-body">
        <el-card shadow="never">
          <el-form label-position="top"
                   :model="form"
                   ref="form"
                   :rules="rules"
                   class="ruleForm">
            <el-form-item label="站点名称"
                          prop="name">
              <el-input maxlength="20"
                        show-word-limit
                        placeholder="请输入站点名称"
                        v-model.trim="form.name"></el-input>
            </el-form-item>
            <el-form-item label="站点域名"
                          prop="url">
              <el-input show-word-limit
                        placeholder="请输入站点域名"
                        v-model.trim="form.url"></el-input>
              <span class="agy">注意:【域名需要加http//或https//开头,例如https://ship.weijuyunke.com】</span>
            </el-form-item>

            <el-form-item v-if="hiddenPassword"
                          label="账号"
                          prop="account_name">
              <el-input maxlength="25"
                        show-word-limit
                        :disabled="isUpdate ? true : false"
                        placeholder="请输入账号"
                        v-model.trim="form.account_name"></el-input>
            </el-form-item>
            <el-form-item v-if="hiddenPassword"
                          label="密码"
                          prop="password">
              <el-input maxlength="25"
                        show-password
                        show-word-limit
                        placeholder="请输入密码"
                        v-model.number="form.password"></el-input>
            </el-form-item>
            <el-form-item v-if="hiddenPassword"
                          label="联系电话"
                          prop="phone">
              <el-input maxlength="11"
                        show-word-limit
                        placeholder="请输入联系电话"
                        v-model.number="form.phone"></el-input>
            </el-form-item>

            <el-form-item label="到期时间:"
                          prop="expire_time">
              <el-date-picker v-model="form.expire_time"
                              type="date"
                              placeholder="选择日期时间">
              </el-date-picker>

            </el-form-item>

            <div class="drawer__footer">
              <el-button round
                         type="plain"
                         @click="handleClose"
                         size="medium">返回</el-button>
              <el-button type="primary"
                         round
                         :loading="loading"
                         size="medium"
                         @click="save">提交</el-button>
            </div>
          </el-form>
        </el-card>
      </div>
    </el-drawer>
    <!-- 图片预览 -->
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
  </div>
</template>
<script>


import ElImageViewer from 'element-ui/packages/image/src/image-viewer';

import { addPlatform, editPlatform } from '@/api/siteList/index';

export default {
  name: 'drawerEdit',
  components: { ElImageViewer },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },

  data () {
    // const logo = (rule, value, callback) => {
    //   console.log(this.form.logo);
    //   if (!this.form.logo) {
    //     callback(new Error('请上传图片'));
    //   } else {
    //     callback();
    //   }
    // };
    // 默认表单数据
    const defaultWhere = {
      // 站点名称
      name: '',
      // 站点域名
      url: '',

      // 联系电话
      phone: '',
      //   账户
      account_name: '',
      //   密码
      password: '',
      // 申请时间
      expire_time: '',

    };

    return {
      isUpdate: false,
      dialogVisible: false,
      viewerVisible: false,
      form: {
        ...defaultWhere
      },
      imgViewArr: [],
      loading: false,
      //  图片回显
      fileList: [],
      sumbitForm: {},
      dialogImageUrl: '',
      imageUrl: '',
      hiddenPassword: true,

      storageMode: '',
      // 正则校验
      rules: {
        name: [
          {
            required: true,
            message: '请输入站点名称',
            trigger: 'blur'
          }
        ],
        url: [
          {
            required: true,
            message: '请输入站点域名',
            trigger: 'blur'
          }
        ],

        account_name: [
          {
            required: true,
            message: '请输入账号',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: 'blur'
          }
        ],
        expire_time: [
          {
            required: true,
            message: '请输入到期时间',
            trigger: 'blur'
          }
        ],
        // 站点 图片上传
        // logo: [{ required: true, validator: logo, trigger: 'change' }]
      }
    };
  },
  created () {

  },
  computed: {
    // 营业执照
    urlListArray () {
      return this.imgViewArr;
    },
    // ** 隐私部分带*号
    hiddenCardId () {
      return function (str, frontLen = 4, endLen = 4) {
        //str：要进行隐藏的变量  frontLen: 前面需要保留几位    endLen: 后面需要保留几位
        var len = str.length - frontLen - endLen;
        var start = '';
        for (var i = 0; i < len; i++) {
          start += '*';
        }
        // 最后的返回值由三部分组成
        return (
          str.substring(0, frontLen) +
          start +
          str.substring(str.length - endLen)
        );
      };
    },
    //  code码获取城市标题

  },
  methods: {
    // 点击按钮预览图片
    handlePictureCardPreview () {
      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgViewArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgViewArr = imgStr.split();
        }

        this.viewerVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    },
    // 关闭查看器
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片



    // 关闭抽屉
    handleClose () {
      this.$confirm('确认关闭？')
        .then(_ => {
          console.log('查看详情');
          this.$emit('update:drawerEditBoolen', false);
        })
        .catch(_ => { });

    },



    // 新增
    save () {
      this.$refs['form'].validate((valid) => {
        console.log('保存提交');
        if (!valid) {
          return false;
        }
        this.loading = true;
        for (const key in this.form) {
          if (key == 'expire_time') {
            console.log(this.form[key]);

            // let startTime = this.form[key]?.[0];
            let endTime = this.form[key];
            // this.sumbitForm['startDate'] =
            //   startTime == undefined ? '' : startTime;
            this.sumbitForm['expire_time'] = endTime == undefined ? '' : endTime;
          } else {
            this.sumbitForm[key] = this.form[key];
          }
        }

        console.log(this.sumbitForm);
        if (this.isUpdate) {
          this.sumbitForm = {
            url: this.form.url,
            name: this.form.name,
            expire_time: this.form.expire_time,
            id: this.form.id,
          }
        }
        const saveOrUpdate = this.isUpdate ? editPlatform : addPlatform;
        saveOrUpdate(this.sumbitForm)
          .then((msg) => {
            console.log(msg);
            this.loading = false;
            this.$message.success(msg);
            if (!this.isUpdate) {
              this.$router.go(0);
            }
            this.$emit('update:drawerEditBoolen', false);
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    }
  },
  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(() => {
        if (visible) {
          console.log(this.$util);
          if (this.data) {
            // 隐藏账号密码

            this.hiddenPassword = false;
            this.form.id = '';
            this.$util.assignObject(this.form, {
              ...this.data
            });




            this.form.expire_time = this.data.expire_time;
            this.isUpdate = true;
          } else {
            this.isUpdate = false;
            this.hiddenPassword = true;
          }
        } else {
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
            this.fileList = [];
          });
        }
      });
    }
  }
};
</script>
<style lang="less">
.agy {
  color: #b5b5b7 !important;
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
}

// /deep/.el-select {
//   width: 100%;
// }
// /deep/.el-cascader--medium {
//   width: 100%;
// }
</style>
